package com.tte.common.schedule;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 原生定时任务测试
 */
@Component
public class ScheduleTest {
    private static Logger logger = LoggerFactory.getLogger(ScheduleTest.class);

    /**
     * 同步信号量
     */
    private static final Semaphore semaphore = new Semaphore(1);
    /**
     * 定时执行
     */
    private static ScheduledExecutorService scheduler = null;

    /**
     * 定时操作线程
     */
    private final static Runnable TodoOperation = new Runnable() {
        public void run() {
            try {
                semaphore.acquire();
                System.out.println("定时执行------执行内容------");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        }
    };

    /**
     * 启动定时器
     */
    public static void start() {

        if (scheduler == null) {
            scheduler = Executors.newScheduledThreadPool(1);

            synchronized (scheduler) {
                /*
                 * TODO 设置定时器启动时间和间隔
                 */
                scheduler.scheduleAtFixedRate(TodoOperation, 0, 10, TimeUnit.SECONDS);
                logger.debug("启动TODO定时器!");
            }

        } else {
            logger.debug("TODO定时器正在运行!");
        }

    }

    /**
     * 停止定时器
     */
    public static void stop() {
        synchronized (scheduler) {
            if (scheduler != null && !scheduler.isShutdown()) {
                scheduler.shutdown();
                scheduler = null;
                logger.debug("关闭TODO定时器!");
            }
        }
    }

    /**
     * 重启定时器
     */
    public static void restart() {
        stop();
        start();
    }

    /**
     * 手动触发
     */
    public static void trigger() {
        TodoOperation.run();
    }

}
